<?php

/**
 *    买家的订单管理控制器
 *
 *    @author    bansen 2014-05-27
 *    @usage    none
 */
class Buyer_orderApp extends MemberbaseApp
{

    function index()
    {
        /* 获取订单列表 */
        $this->_get_orders();

        /* 当前位置 */
        switch ($_GET['type'])
        {
            case 'all_orders':
                $lg = LANG::get('all_order');
                break;
            case 'pending':
                $lg = LANG::get('pending');
                break;
            case 'accepted':
                $lg = LANG::get('accepted');
                break;
            case 'shipped':
                $lg = LANG::get('shipped');
                break;
            case 'finished':
                $lg = LANG::get('finished');
                break;
            case 'canceled':
                $lg = LANG::get('canceled');
                break;
            case 'evalua':
                $lg = LANG::get('evalua');
                break;
            default:
                $lg = LANG::get('all_order');
        }
        $this->_curlocal(LANG::get('member_center'), 'index.php?app=member', LANG::get('buyer_goods'), 'index.php?app=buyer_order', $lg);

        /* 当前用户中心菜单 */
        $this->_curitem('buyer_goods');
        $this->_curmenu('order_list');
        $this->assign('gets', $_GET);
        $this->_config_seo('title', Lang::get('member_center') . ' - ' . Lang::get('my_order'));

        /* 买家提醒：待付款、待确认、待评价订单数 */
        $order_mod = & m('order');
        $returns_mod =& m('returns');
        $sql = "SELECT 
                count(case when status = '" . ORDER_PENDING . "' then order_id end) submitted,
                count(case when status = '" . ORDER_SHIPPED . "' then order_id end) shipped,
                count(case when status = '" . ORDER_ACCEPTED . "' then order_id end) accepted,
                count(case when status = '" . ORDER_FINISHED . "' AND evaluation_status = 0 then order_id end) evalua
                FROM {$order_mod->table} where buyer_id = '{$_SESSION['user_info']['user_id']}'";      
        $buyer_stat = $order_mod->getRow($sql);
        $sql11 = "SELECT COUNT(returns_id) FROM {$returns_mod->table} WHERE buyer_id = '{$_SESSION['user_info']['user_id']}' AND status IN (1,3,4,5,6,7)";
        $buyer_stat['returns'] = $returns_mod->getOne($sql11);
        $this->assign('buyer_stat', $buyer_stat);
        $this->import_resource(array(
            'script' => array(
                array(
                    'path' => 'dialog/dialog.js',
                    'attr' => 'id="dialog_js"',
                ),
                array(
                    'path' => 'jquery.ui/jquery.ui.js',
                    'attr' => '',
                ),
                array(
                    'path' => 'jquery.ui/i18n/' . i18n_code() . '.js',
                    'attr' => '',
                ),
                array(
                    'path' => 'jquery.plugins/jquery.validate.js',
                    'attr' => '',
                ),
            ),
            'style' => 'jquery.ui/themes/ui-lightness/jquery.ui.css',
        ));


        /* 显示订单列表 */
        $this->display('buyer_order.index.html');
    }

    /**
     *    评价管理
     *
     *    @author   yanghj 2014.6.5
     *    @param    none
     *    @return    void
     */
    function evalua()
    {

        $model_comment = & m('comment');
        $page = $this->_get_page();    //获取分页信息
        $evalua_goods = $model_comment->find(array(
            'join' => 'has_order,has_ordergoods',
            'fields' => 'comment.comment_id, comment.order_id, comment.goods_id, comment.comment, comment.evaluation, comment.add_time, comment.is_edit, order.order_sn, order.seller_name, ordergoods.goods_name',
            'conditions' => 'comment.order_id=order_goods.order_id AND comment.comment_type=0 AND comment.is_valid =1 AND comment.from_user_id =' . $this->visitor->get('user_id'),
            'count' => true,
            'order' => 'comment.is_edit ASC, comment.add_time DESC',
            'limit' => $page['limit'],
        ));
        $page['item_count'] = $model_comment->getCount();   //获取统计的数据
        $this->_format_page($page);

        $this->_curlocal(LANG::get('buyer_center'), 'index.php?app=member', LANG::get('review'), 'index.php?app=buyer_order&act=evalua', LANG::get('评价列表'));
        $this->_curitem('review');
        $this->assign('evalua_goods', $evalua_goods);
        $this->assign('page_info', $page);          //将分页信息传递给视图，用于形成分页条
        $this->_config_seo('title', Lang::get('buyer_center') . ' - ' . Lang::get('review'));
        $this->display('buyer_evalua.index.html');
    }

    /**
     *    编辑评价管理
     *
     *    @author   yanghj 2014.6.6
     *    @param    none
     *    @return    void
     */
    function evalua_edit()
    {
        $comment_id = empty($_GET['comment_id']) ? 0 : intval($_GET['comment_id']);
        if (!$comment_id)
        {
            $this->show_warning('没有相关的评价');
            return;
        }
        $model_comment = & m('comment');
        if (!IS_POST)
        {
            $comment_data = $model_comment->get(array(
                'join' => 'has_ordergoods',
                'fields' => 'comment.comment_id, comment.order_id, comment.goods_id, comment.comment, comment.evaluation, ordergoods.goods_name, ordergoods.goods_image',
                'conditions' => 'comment.is_edit=0 AND comment.comment_id = ' . $comment_id . ' AND comment.from_user_id =' . $this->visitor->get('user_id'),
            ));
            if (empty($comment_data))
            {
                $this->show_warning('没有相关的评价');

                return;
            }

            $this->_curlocal(LANG::get('buyer_center'), 'index.php?app=member', LANG::get('review'), 'index.php?app=buyer_order&act=evalua', LANG::get('编辑评价'));
            $this->_curitem('review');
            $this->assign('comment', $comment_data);
            $this->_config_seo('title', Lang::get('buyer_center') . ' - ' . Lang::get('review'));
            $this->display('buyer_evalua.edit.html');
        }
        else
        {
            if (!$_POST['comment'])
            {
                $this->show_warning('商品评价内容不能为空');
                return;
            }
            $data = array(
                'evaluation' => intval($_POST['evaluation']),
                'comment' => strip_tags(trim($_POST['comment'])),
                'is_edit' => 1,
                'add_time' => gmtime()
            );
            $model_comment->edit($comment_id, $data);
            if ($model_comment->has_error())
            {
                $this->show_warning($model_comment->get_error());
                return;
            }

            $this->show_message('修改商品评价成功', 'back_list', 'index.php?app=buyer_order&act=evalua');
        }
    }

    /**
     *    查看订单详情
     *
     *    @author    Garbin
     *    @return    void
     */
    function view()
    {
        $order_id = isset($_GET['order_id']) ? intval($_GET['order_id']) : 0;
        $model_order = & m('order');
        //$order_info  = $model_order->get("order_id={$order_id} AND buyer_id=" . $this->visitor->get('user_id'));
        $order_info = $model_order->get(array(
            'fields' => "this.*,store.store_name,store.owner_name",
            'conditions' => "order_id={$order_id} AND buyer_name='{$this->visitor->get('user_name')}'",
            'join' => 'belongs_to_store',
        ));

        if (!$order_info)
        {
            $this->show_warning('no_such_order');

            return;
        }
        //获取买家信息
        $orderextm_mod = & m('orderextm');
        $order_info['orderextm_info'] = $orderextm_mod->get_info($order_id);
        //print_r($order_info);
        //获取卖家发货地址
        $selleraddress_mod = & m('selleraddress');
        $order_info['seller_address_info'] = $selleraddress_mod->get(array(
            'fields' => 'phone_mob,phone_tel,region_name,address',
            'conditions' => 'user_id=' . $order_info['seller_id'] . ' and type=0',
            'order' => 'is_deafult desc',
            'limit' => '1',
        ));

        /* 团购信息 */
        /* if ($order_info['extension'] == 'groupbuy')
          {
          $groupbuy_mod = &m('groupbuy');
          $group = $groupbuy_mod->get(array(
          'join' => 'be_join',
          'conditions' => 'order_id=' . $order_id,
          'fields' => 'gb.group_id',
          ));
          $this->assign('group_id',$group['group_id']);
          } */

        /* 当前位置 */
        $this->_curlocal(LANG::get('member_center'), 'index.php?app=member', LANG::get('buyer_goods'), 'index.php?app=buyer_order', LANG::get('view_order'));

        /* 当前用户中心菜单 */
        $this->_curitem('buyer_goods');

        $this->_config_seo('title', Lang::get('member_center') . ' - ' . Lang::get('order_detail'));

        /* 调用相应的订单类型，获取整个订单详情数据 */
        $order_type = & ot($order_info['extension']);
        $order_detail = $order_type->get_order_detail($order_id, $order_info);
        $spec_ids = array();
        foreach ($order_detail['data']['goods_list'] as $key => $goods)
        {
            empty($goods['goods_image']) && $order_detail['data']['goods_list'][$key]['goods_image'] = Conf::get('default_goods_image');
            $spec_ids[] = $goods['spec_id'];
        }
        
        /* 查出最新的相应的货号 */
        $model_spec = & m('goodsspec');
        $spec_info = $model_spec->find(array(
            'conditions' => "spec_id" . db_create_in($spec_ids),
            'fields' => 'sku',
        ));
        foreach ($order_detail['data']['goods_list'] as $key => $goods)
        {
            $order_detail['data']['goods_list'][$key]['sku'] = $spec_info[$goods['spec_id']]['sku'];
            $order_detail['data']['goods_list'][$key]['total_money'] = $goods['quantity'] * $goods['price'];
        }
        
        $orderStatus = array(1 => 11, 2 => 20, 3 => 30, 4 => 40);
        $showProgress = in_array($order_info['status'], $orderStatus);
        $progressId = array_search($order_info['status'], $orderStatus);
        //vdump($order_info);
        $this->assign('order', $order_info);
        $this->assign($order_detail['data']);
        $this->assign('progressId', $progressId);
        $this->assign('showProgress', $showProgress);
        $this->assign('left_time', $this->_get_time_by_status($order_info));
        $this->assign("pop_dialog", $_GET['pop']);
        $this->import_resource(array(
            'script' => array(
                array(
                    'path' => 'dialog/dialog.js',
                    'attr' => 'id="dialog_js"',
                ),
                array(
                    'path' => 'jquery.ui/jquery.ui.js',
                    'attr' => '',
                ),
                array(
                    'path' => 'jquery.ui/i18n/' . i18n_code() . '.js',
                    'attr' => '',
                ),
                array(
                    'path' => 'jquery.plugins/jquery.validate.js',
                    'attr' => '',
                ),
            ),
            'style' => 'jquery.ui/themes/ui-lightness/jquery.ui.css',
        ));
        $this->display('buyer_order.view.html');
    }

    /**
     *    取消订单
     *
     *    @author    Garbin
     *    @return    void
     */
    function cancel_order()
    {

        $order_id = isset($_GET['order_id']) ? intval($_GET['order_id']) : 0;
        if (!$order_id)
        {
            echo Lang::get('no_such_order');

            return;
        }
        $model_order = & m('order');
        /* 只有待付款的订单可以取消 */
        $order_info = $model_order->get("order_id={$order_id} AND buyer_id=" . $this->visitor->get('user_id') . " AND status " . db_create_in(array(ORDER_PENDING, ORDER_SUBMITTED)));
        if (empty($order_info))
        {
            echo Lang::get('no_such_order');

            return;
        }
        if (!IS_POST)
        {
            header('Content-Type:text/html;charset=' . CHARSET);
            $this->assign('order', $order_info);
            $this->display('buyer_order.cancel.html');
        }
        else
        {
            $model_order->edit($order_id, array('status' => ORDER_CANCELED));
            if ($model_order->has_error())
            {
                $this->pop_warning($model_order->get_error());

                return;
            }

            /* 加回商品库存 */
            $model_order->change_stock('+', $order_id);
            $cancel_reason = (!empty($_POST['remark'])) ? strip_tags($_POST['remark']) : $_POST['cancel_reason'];
            /* 记录订单操作日志 */
            $order_log = & m('orderlog');
            $order_log->add(array(
                'order_id' => $order_id,
                'operator' => addslashes($this->visitor->get('user_name')),
                'order_status' => order_status($order_info['status']),
                'changed_status' => order_status(ORDER_CANCELED),
                'remark' => $cancel_reason,
                'log_time' => gmtime(),
            ));

            /* 发送给卖家订单取消通知 */
//            $model_member = & m('member');
//            $seller_info = $model_member->get($order_info['seller_id']);
            $model_usersafety = & m('usersafety');
            $seller_info = $model_usersafety->get("user_id='{$order_info['seller_id']}'");
            $mail = get_mail('toseller_cancel_order_notify', array('order' => $order_info, 'reason' => $_POST['remark']));
            if($seller_info['binding_email']){
                $this->_mailto($seller_info['binding_email'], addslashes($mail['subject']), addslashes($mail['message']));
            }
            
            //解冻余额
            $this->_unfreeze($order_id);

            $this->pop_warning('ok');
        }
    }

    /**
     *    确认订单
     *
     *    @author    Garbin
     *    @return    void
     */
    function confirm_order()
    {
        $order_id = isset($_GET['order_id']) ? intval($_GET['order_id']) : 0;
        if (!$order_id)
        {
            echo Lang::get('no_such_order');

            return;
        }
        $model_order = & m('order');
        /* 只有已发货的订单可以确认 */
        $order_info = $model_order->get("order_id={$order_id} AND buyer_id=" . $this->visitor->get('user_id') . " AND status=" . ORDER_SHIPPED);
        if (empty($order_info))
        {
            echo Lang::get('no_such_order');

            return;
        }
        
        $mode_usersatety =& m('usersafety');
        $satety_info = $mode_usersatety->get(array(
            'fields' => "pay_password",
            'conditions' => "user_id={$order_info['buyer_id']}",
        ));
            
        if (!IS_POST)
        {
            header('Content-Type:text/html;charset=' . CHARSET);
            $this->assign('order', $order_info);
            $this->assign("has_pass", $satety_info['pay_password']);
            $this->display('buyer_order.confirm.html');
        }
        else
        {
            //判断支付密码是否正确
            $bool = $this->_comp_pay_passw($satety_info);
            if(!$bool)
                return;
            
            $model_order->edit($order_id, array('status' => ORDER_FINISHED, 'finished_time' => gmtime()));
            if ($model_order->has_error())
            {
                $this->pop_warning($model_order->get_error());

                return;
            }

            /* 记录订单操作日志 */
            $order_log = & m('orderlog');
            $order_log->add(array(
                'order_id' => $order_id,
                'operator' => addslashes($this->visitor->get('user_name')),
                'order_status' => order_status($order_info['status']),
                'changed_status' => order_status(ORDER_FINISHED),
                'remark' => Lang::get('buyer_confirm'),
                'log_time' => gmtime(),
            ));

            /* 发送给卖家买家确认收货邮件，交易完成 */
//            $model_member = & m('member');
//            $seller_info = $model_member->get($order_info['seller_id']);
            $model_usersafety = & m('usersafety');
            $seller_info = $model_usersafety->get("user_id='{$order_info['seller_id']}'");
            $mail = get_mail('toseller_finish_notify', array('order' => $order_info));
            if($seller_info['binding_email']){
                $this->_mailto($seller_info['binding_email'], addslashes($mail['subject']), addslashes($mail['message']));
            }

            $new_data = array(
                'status' => Lang::get('order_finished'),
                'actions' => array('evaluate'),
            );

            /* 更新累计销售件数 */
            $model_goodsstatistics = & m('goodsstatistics');
            $model_ordergoods = & m('ordergoods');
            $order_goods = $model_ordergoods->find("order_id={$order_id}");
            foreach ($order_goods as $goods)
            {
                $model_goodsstatistics->edit($goods['goods_id'], "sales=sales+{$goods['quantity']}");
            }
            
            //关闭退货退款申请
            $this->_close_returns($order_id);
            
            //发送手机短信
            $model_order_extm = & m('orderextm');
            $mobile = $model_order_extm->get_fields_name($order_id,'phone_mob');
            if(!empty($mobile) && is_mobile($mobile))
            {
                $msg = '尊敬的会员，感谢您确认收货，祝购物愉快。如对商品有任何问题，可致电客服020-83281328。';
                include(ROOT_PATH.'/includes/sendsms/ueswt.php');
                $gckj = new ueswt();
                $gckj->send_sms($msg,$mobile);               
            }
            
            $this->pop_warning("ok");
        }
    }

    /**
     *    给卖家评价
     *
     *    @author    yanghj 2014.6.5
     *    @param    none
     *    @return    void
     */
    function evaluate()
    {
        $order_id = isset($_GET['order_id']) ? intval($_GET['order_id']) : 0;
        if (!$order_id)
        {
            $this->show_warning('no_such_order');

            return;
        }

        /* 验证订单有效性 */
        $model_order = & m('order');
        $order_info = $model_order->get("order_id={$order_id} AND buyer_id=" . $this->visitor->get('user_id'));
        if (!$order_info)
        {
            $this->show_warning('no_such_order');

            return;
        }
        if ($order_info['status'] != ORDER_FINISHED)
        {
            /* 不是已完成的订单，无法评价 */
            $this->show_warning('cant_evaluate');

            return;
        }
        if ($order_info['evaluation_status'] == 1)
        {
            /* 已评价的订单 */
            $this->show_warning('already_evaluate');

            return;
        }
        $model_ordergoods = & m('ordergoods');

        if (!IS_POST)
        {
            /* 显示评价表单 */
            /* 获取订单商品 */
            $goods_list = $model_ordergoods->find("order_id={$order_id}");
            foreach ($goods_list as $key => $goods)
            {
                empty($goods['goods_image']) && $goods_list[$key]['goods_image'] = Conf::get('default_goods_image');
            }
            $this->_curlocal(LANG::get('member_center'), 'index.php?app=member', LANG::get('my_order'), 'index.php?app=buyer_order', LANG::get('evaluate'));
            //var_dump($goods_list);
            $this->assign('goods_list', $goods_list);
            $this->assign('order', $order_info);
            $this->_config_seo('title', Lang::get('member_center') . ' - ' . Lang::get('credit_evaluate'));
            $this->display('buyer_order.evaluate.html');
        }
        else
        {
            $evaluations = array();
            /* 写入评价 */

            foreach ($_POST['evaluations'] as $rec_id => $evaluation)
            {
                if ($evaluation['evaluation'] <= 0 || $evaluation['evaluation'] > 5)
                {
                    $this->show_warning('evaluation_error');

                    return;
                }
                /* switch ($evaluation['evaluation'])
                  {
                  case 3:
                  $credit_value = 1;
                  break;
                  case 1:
                  $credit_value = -1;
                  break;
                  default:
                  $credit_value = 0;
                  break;
                  } */
                $evaluations[intval($rec_id)] = array(
                    'comment_type' => 0,
                    'order_id' => $order_id,
                    'goods_id' => intval($evaluation['goods_id']),
                    'from_user_name' => $this->visitor->get('user_name'),
                    'evaluation' => $evaluation['evaluation'],
                    'comment' => strip_tags($evaluation['comment']),
                    'add_time' => gmtime(),
                    'to_user_id' => $order_info['seller_id'],
                    'from_user_id' => $this->visitor->get('user_id'),
                    'credit_value' => 0,
                    'quantity' => intval($evaluation['quantity'])
                );
            }
            if ($_POST['bedlevel'] <= 0 || $_POST['bedlevel'] > 3)
            {
                $this->show_warning('evaluation_error');

                return;
            }
            $store_comment = array(
                'comment_type' => 1,
                'order_id' => $order_id,
                'from_user_name' => $this->visitor->get('user_name'),
                'evaluation' => intval($_POST['bedlevel']),
                'comment' => '',
                'add_time' => gmtime(),
                'to_user_id' => $order_info['seller_id'],
                'from_user_id' => $this->visitor->get('user_id'),
                'credit_value' => 0
            );
            $model_comment = & m('comment');
            $model_comment->add($store_comment); //写入买家对商铺评价
            $goods_list = $model_ordergoods->find("order_id={$order_id}");
            foreach ($evaluations as $rec_id => $evaluation)
            {
                $model_comment->add($evaluation); //写入商品评价
                $goods_url = SITE_URL . '/' . url('app=goods&id=' . $goods_list[$rec_id]['goods_id']);
                $goods_name = $goods_list[$rec_id]['goods_name'];
                $this->send_feed('goods_evaluated', array(
                    'user_id' => $this->visitor->get('user_id'),
                    'user_name' => $this->visitor->get('user_name'),
                    'goods_url' => $goods_url,
                    'goods_name' => $goods_name,
                    'evaluation' => Lang::get('order_eval.' . $evaluation['evaluation']),
                    'comment' => $evaluation['comment'],
                    'images' => array(
                        array(
                            'url' => SITE_URL . '/' . $goods_list[$rec_id]['goods_image'],
                            'link' => $goods_url,
                        ),
                    ),
                ));
            }

            /* 更新订单评价状态 */
            $model_order->edit($order_id, array(
                'evaluation_status' => 1,
                'evaluation_time' => gmtime()
            ));

            /* 更新卖家信用度及好评率 */
            /* $model_store =& m('store');
              $model_store->edit($order_info['seller_id'], array(
              'credit_value'  =>  $model_store->recount_credit_value($order_info['seller_id']),
              'praise_rate'   =>  $model_store->recount_praise_rate($order_info['seller_id'])
              )); */

            /* 更新商品评价数 */
            $model_goodsstatistics = & m('goodsstatistics');
            $goods_ids = array();
            foreach ($goods_list as $goods)
            {
                $goods_ids[] = $goods['goods_id'];
            }
            $model_goodsstatistics->edit($goods_ids, 'comments=comments+1');


            $this->show_message('evaluate_successed', 'back_list', 'index.php?app=buyer_order');
        }
    }

    /**
     *    获取订单列表
     *
     *    @author    Garbin
     *    @return    void
     */
    function _get_orders()
    {
        $page = $this->_get_page(10);
        $model_order = & m('order');
        $type = isset($_GET['type']) ? html_script($_GET['type']) : 'all_orders';
        $query = $_GET;
        $query['search_name'] = html_script($query['search_name']);
        $query['order_sn'] = html_script($query['order_sn']);
        $query['goods_name'] = html_script($query['goods_name']);

        if($type != 'all_orders' && !empty($type))
        {
            if ($_GET['type'] == 'evalua')
            {
                $conditions = " AND status = " . ORDER_FINISHED . " AND evaluation_status = 0 ";
            }
            else
            {
                if(order_status_translator($type) !== '')
                {
                    $conditions = " AND status=".order_status_translator($type);
                }

            }
        }
        else
        {
            $conditions = $this->_condition_by_params();
        }

        /* 查找订单 */
        $orders = $model_order->findAll(array(
            'conditions' => "buyer_id=" . $this->visitor->get('user_id') . "{$conditions}",
            'fields' => 'this.*,orderextm.shipping_fee,orderextm.free_shipping,orderextm.shipping_code',
            'count' => true,
            'join' => 'has_orderextm',
            'limit' => $page['limit'],
            'order' => 'add_time DESC',
            'include' => array(
                'has_ordergoods', //取出商品
            ),
        ));

        $spec_ids = array();
        foreach ($orders as $key1 => $order)
        {
            if($order['free_shipping'] > 0 || $order['discount'] > 0){
                $orders[$key1]['old_order_amount'] = $order['goods_amount'] + $order['shipping_fee'];
            }
            if (isset($order['order_goods']) && is_array($order['order_goods']))
                foreach ($order['order_goods'] as $key2 => $goods)
                {
                    $spec_ids[] = $goods['spec_id'];
                }
        }
        /* 查出最新的相应的货号 */
        $model_spec = & m('goodsspec');
        $spec_info = $model_spec->find(array(
            'conditions' => "spec_id " . db_create_in($spec_ids) ,
            'fields' => 'sku',
        ));
        
        foreach ($orders as $key1 => $order)
        {
            if (isset($order['order_goods']) && is_array($order['order_goods']))
            {
                $ak = array_keys($order['order_goods']);
                $orders[$key1]['index'] = $ak[0];
                $orders[$key1]['endtime'] = date('m/d/Y H:s:m', $order['add_time'] + 604800);
                foreach ($order['order_goods'] as $key2 => $goods)
                {
                    empty($goods['goods_image']) && $orders[$key1]['order_goods'][$key2]['goods_image'] = Conf::get('default_goods_image');
                    $orders[$key1]['order_goods'][$key2]['sku'] = $spec_info[$goods['spec_id']]['sku'];
                }
                $orders[$key1]['is_mobile'] = (strpos($order['payment_code'], "wap") !== false) ? true : false;
                $orders[$key1]['close_returns'] = ($order['finished_time'] && time() - $order['finished_time'] > 7*3600) ? true : false;
            }
        }

        $page['item_count'] = $model_order->getCount();
        $this->assign('order_status_list', array(
            ORDER_PENDING => '待付款',
            ORDER_ACCEPTED => '待发货',
            ORDER_SHIPPED =>  '待确认收货',
            ORDER_FINISHED => '交易成功',
            ORDER_CANCELED => '交易取消',
            ORDER_CLOSED =>   '交易关闭',
        ));
        $this->assign('evaluation_status_list', array(
            '0' => '需我评价',
            '1' => '已评价',
        ));
        $this->assign('type', $type);
        $this->assign('query', $query);
        $this->_format_page($page);
        $this->assign('page_info', $page);
        $this->assign('orders', $orders);
    }

    //搜索查询条件
    function _condition_by_params()
    {
        $condition = "";
        if($_GET['status'] !== '' && isset($_GET['status']))
        {
            $condition .= " AND status =" . intval($_GET['status']);
        }
        if($_GET['evaluation_status'] !== '' && isset($_GET['evaluation_status']))
        {
            $condition .= " AND evaluation_status =" . intval($_GET['evaluation_status']);
        }
        if(!empty($_GET['search_name']))
        {
            $condition .= " AND seller_name LIKE '%".html_script($_GET['search_name'])."%'";
        }
        if(!empty($_GET['order_sn']))
        {
            $condition .= " AND order_sn LIKE '%".html_script($_GET['order_sn'])."%'";
        }
        if(!empty($_GET['add_time_from_date']))
        {
            $add_time_from = trim($_GET['add_time_from_date']);
            $condition .= " AND add_time >=" . gmstr2time($add_time_from);
        }
        if(!empty($_GET['add_time_to_date']))
        {

            $add_time_to = trim($_GET['add_time_to_date']);
            $condition .= " AND add_time <" . gmstr2time_end($add_time_to);
        }
        if(!empty($_GET['goods_name']))
        {
            $condition1 = " goods_name LIKE '%".html_script($_GET['goods_name'])."%' OR sku LIKE '%".html_script($_GET['goods_name'])."%'";
            $ordergoods_mod =& m('ordergoods');
            $sql = "select distinct og.order_id from {$ordergoods_mod->table} og left join ".DB_PREFIX."goods_spec gs on og.spec_id=gs.spec_id where {$condition1}";
            $order_ids = $ordergoods_mod->getCol($sql);
            if(is_array($order_ids))
            {
                $condition .= ' AND order_alias.order_id' . db_create_in($order_ids);
            }
            else
            {
                return false;
            }
        }

        return $condition;
    }

    function _get_member_submenu()
    {
        $menus = array(
            array(
                'name' => 'order_list',
                'url' => 'index.php?app=buyer_order',
            ),
        );
        return $menus;
    }
    
    private function _get_time_by_status($order)
    {
        $result = 0;
        $status = $order['status'];
        $timeStatus = array(
            11 => array('time' => 3 * 24 * 3600, 'field' => 'add_time') ,
            30 => array('time' => 10 * 24 * 3600, 'field' => 'ship_time') ,
        );
        
        if(in_array($status, array_keys($timeStatus))){
            $result = $order[$timeStatus[$status]['field']] + $timeStatus[$status]['time'] - time();
        }
        return $result;
    }
    
    private function _close_returns($order_id)
    {
        $model_returns = & m('returns');
        $model_returns->close_returns($order_id, 1);
    }
    
    private function _comp_pay_passw($satety_info)
    {
        $pay_passw = trim($_POST['pay_passw']);
        if(empty($pay_passw))
        {
            $this->pop_warning("请填入支付密码");
            return 0;
        }
        $pay_passw = md5(md5($pay_passw, true));
            
        if(!$satety_info['pay_password'])
        {
            $this->pop_warning("请先设置支付密码，<a target=_blank href=index.php?app=account_security&act=authen_verify&mode=set_pay_password&from=buyer>点此设置</a>");
            return 0;
        }
            
        if($pay_passw != $satety_info['pay_password'])
        {
            $this->pop_warning("您输入的密码错误，请重新输入");
            return 0;
        }
        
        return 1;
        
    }
    
    private function _unfreeze($order_id)
    {
        $orderpay_mod = m("orderpay");
        $orderpay = $orderpay_mod->find(array(
            'conditions' => "user_id = {$this->visitor->get('user_id')} AND order_id = '{$order_id}' AND flag = 0 AND pay_time = 0 group by order_id",
            'fields' => 'sum(balance_price) balance_price,out_trade_sn',
        ));
            
        $orderpay = array_values($orderpay);
        
        $bool = $orderpay_mod->edit("out_trade_sn = '{$orderpay[0]['out_trade_sn']}'", array('flag' => 1));
        if($bool){
            $usermoney_mod = m("usermoney");
            $sql = "update wl_user_money set user_money = (user_money + {$orderpay[0]['balance_price']}), frozen_money = (frozen_money - {$orderpay[0]['balance_price']}) where user_id = '{$this->visitor->get('user_id')}'";
            $usermoney_mod->db->query($sql);
        }
    }
    

}

?>
